import { defineStore } from 'pinia';
import { ref } from 'vue';

interface ThemeColors {
    primary: string;
    secondary: string;
    tabBarBackground: string;
    tabBarColor: string;
    tabBarSelectedColor: string;
}

interface Theme {
    id: string;
    name: string;
    colors: ThemeColors;
}

// 创建全局状态
export const isDarkMode = ref<boolean>(false);  // 初始值设为false，避免闪烁
export const currentTheme = ref<string>('theme-baby');  // 设置默认主题

// 移除动画配置
const ANIMATION_DURATION = 0;
const ANIMATION_TIMING = 'linear';
const ANIMATION_DELAY = 0;

// 主题列表
export const themes: Theme[] = [
    { id: 'theme-default', name: '默认主题', colors: { primary: '#8E2DE2', secondary: '#4A00E0', tabBarBackground: '#F6F9FE', tabBarColor: '#999999', tabBarSelectedColor: '#F2BC4C' } },
    { id: 'theme-wedding', name: '婚礼主题', colors: { primary: '#FF9999', secondary: '#FF5E5E', tabBarBackground: '#F6F9FE', tabBarColor: '#999999', tabBarSelectedColor: '#F2BC4C' } },
    { id: 'theme-baby', name: '满月主题', colors: { primary: '#5B9EE7', secondary: '#4A7FBA', tabBarBackground: '#F6F9FE', tabBarColor: '#999999', tabBarSelectedColor: '#F2BC4C' } },
];

// 预加载主题设置
const preloadTheme = () => {
    const cachedDarkMode = uni.getStorageSync('isDarkMode');
    const cachedTheme = uni.getStorageSync('currentTheme');

    // 同步设置主题，避免闪烁
    isDarkMode.value = !!cachedDarkMode;
    currentTheme.value = cachedTheme || 'theme-baby';

    // 立即更新样式
    updateThemeStyle();
};

// 更新主题样式
const updateThemeStyle = async () => {
    // 同步更新所有主题相关的样式
    await Promise.all([
        updateNavigationBarStyle(),
        updateTabBarStyle()
    ]).catch(error => {
        console.error('更新主题样式失败:', error);
    });
};

// 切换暗黑模式
export const toggleDarkMode = async (): Promise<void> => {
    isDarkMode.value = !isDarkMode.value;

    // 保存设置
    uni.setStorageSync('isDarkMode', isDarkMode.value);

    // 立即更新所有样式
    await updateThemeStyle();
};

// 更新导航栏样式
export const updateNavigationBarStyle = async (): Promise<void> => {
    const theme = themes.find(t => t.id === currentTheme.value);
    if (!theme) return;

    return new Promise((resolve) => {
        uni.setNavigationBarColor({
            frontColor: isDarkMode.value ? '#ffffff' : '#000000',
            backgroundColor: isDarkMode.value ? '#1a1a1a' : theme.colors.tabBarBackground,
            animation: {
                duration: 0,
                timingFunc: 'linear'
            },
            complete: () => resolve()
        });
    });
};

// 更新tabBar样式
export const updateTabBarStyle = async (): Promise<void> => {
    const theme = themes.find(t => t.id === currentTheme.value);
    if (!theme) return;

    // 获取当前页面路径
    const pages = getCurrentPages();
    const currentRoute = pages[pages.length - 1]?.route || '';

    // 检查当前页面是否为TabBar页面
    const tabBarPages = ['pages/index/index', 'pages/tip/index', 'pages/my/index'];
    // if (!tabBarPages.includes(currentRoute)) {
    //     return; // 如果不是TabBar页面，直接返回
    // }

    return new Promise((resolve) => {
        console.log(theme.colors.tabBarBackground);
        // 同步更新tabBar样式
        uni.setTabBarStyle({
            color: isDarkMode.value ? 'rgba(255, 255, 255, 0.6)' : theme.colors.tabBarColor,
            selectedColor: isDarkMode.value ? 'rgba(255, 255, 255, 0.9)' : theme.colors.tabBarSelectedColor,
            backgroundColor: isDarkMode.value ? '#1a1a1a' : theme.colors.tabBarBackground,
            borderStyle: isDarkMode.value ? 'white' : 'black',
            animation: {
                duration: 0,
                timingFunc: 'linear'
            }
        });

        // 立即更新所有tab图标
        const tabList = [
            { index: 0, pagePath: 'pages/index/index' },
            { index: 1, pagePath: 'pages/tip/index' },
            { index: 2, pagePath: 'pages/my/index' }
        ];

        // 同步更新所有tab的图标颜色
        tabList.forEach(tab => {
            uni.setTabBarItem({
                index: tab.index,
                selectedColor: isDarkMode.value ? 'rgba(255, 255, 255, 0.9)' : theme.colors.tabBarSelectedColor,
                color: isDarkMode.value ? 'rgba(255, 255, 255, 0.6)' : theme.colors.tabBarColor,
            });
        });

        resolve();
    });
};

// 切换主题
export const changeTheme = async (themeId: string): Promise<void> => {
    currentTheme.value = themeId;
    uni.setStorageSync('currentTheme', themeId);

    // 同步更新样式，无延迟
    await updateThemeStyle();
};

// 初始化主题
export const initTheme = async (): Promise<void> => {
    // 预加载主题设置
    preloadTheme();

    // 立即更新样式
    await updateThemeStyle();
};

// 使用 Pinia store 管理主题状态
export const useThemeStore = defineStore('theme', {
    state: () => ({
        isDark: isDarkMode.value
    }),
    actions: {
        async toggleTheme() {
            await toggleDarkMode();
            this.isDark = isDarkMode.value;
        },
        async initTheme() {
            await initTheme();
            this.isDark = isDarkMode.value;
        }
    },
    getters: {
        currentTheme: (state) => state.isDark ? 'dark' : 'light'
    }
}); 